import 'dart:convert';


import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../Login/LoginVIewController.dart';
import '../Main/InformationView.dart';

class getApiManager {
  static Dio _dio = Dio();

  static Future<void> _handleRequest(
      BuildContext context,
      String url,
      Map<String, dynamic>? queryParameters,
      Function(Map<String, dynamic> responseData) onSuccess,
      ) async {
    String? token = await TokenManager.getToken();
    LoadingDialog.show(context);
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        // 在请求之前添加请求头
        options.headers["satoken"] = token; // 假设 token 已经定义
        return handler.next(options);
      },
    ));

    try {
      Response response = await _dio.get(
        MyServiceUrl.header + url,
        queryParameters: queryParameters,
        options: Options(
          sendTimeout: Duration(seconds: 2),
          receiveTimeout: Duration(seconds: 50),
        ),
        onReceiveProgress: (a, b) => print('received ${a / b}'),
      );
      Map<String, dynamic> jsonMap = json.decode(response.toString());
      // 处理返回的数据
      _handleResponse(context, jsonMap, onSuccess);
    } catch (error) {
      LoadingDialog.hide(context);
      // BrnToast.show(error.toString(), context);
      print(error);
      _handleError(context, error);
    }
  }

  static Future<void> getData(
      BuildContext context,
      String url,
      Map<String, dynamic>? queryParameters,
      Function(Map<String, dynamic> responseData) onSuccess,
      ) async {
    _handleRequest(context, url, queryParameters, onSuccess);
  }

  static void _handleResponse(BuildContext context, Map<String, dynamic> responseData, Function(Map<String, dynamic> responseData) onSuccess) {
    String code = responseData['code'].toString();
    LoadingDialog.hide(context);
    print(responseData);
    if (code == "200") {
      onSuccess(responseData);
    }else if(code == "50010001"||code == "50010002"||code == "50010007"||code == "50010008"||code == "50010009"){
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return BrnDialog(
            titleText: responseData['msg'],
            actionsWidget: [
              TextButton(
                onPressed: () {
                  TokenManager.clearToken();
                  if(code=="50010001") {
                    Navigator.of(context).pushAndRemoveUntil(
                        MaterialPageRoute(builder: (builder) {
                          return LoginVC(backType: 2,);
                        }), (route) => route == null);
                  }else {
                    Navigator.of(context).pushAndRemoveUntil(
                        MaterialPageRoute(builder: (builder) {
                          return LoginVC(backType: 1,);
                        }), (route) => route == null);
                  }
                },
                child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
              ),
            ],
          );
        },
      );
    }else if(code == "500100031"||code == "500100032"||code == "500100033"){
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return BrnDialog(

            titleText: responseData['msg'].replaceAll("无权限：", ""),
            messageText:code =="500100032"?"请先完成身份、驾驶证、行驶证认证":code =="500100033"?"请先完成身份、驾驶证、行驶证、道路运输证、从业资格认证":"请先完成实名认证",
            actionsWidget: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  Navigator.push( context, FadeRoute(page:InformationView(dataMap: {}, isAdd: false,)));
                },
                child: Text("前往认证",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
              ),
            ],
          );
        },
      );
    } else {
      // 处理其他状态码
      // 例如：处理非200状态码的逻辑
      // 这里只是简单示例，您可以根据实际情况进行处理
      BrnToast.show(responseData['msg'], context);
    }
  }

  static void _handleError(BuildContext context, dynamic error) {
    // 根据具体错误类型进行处理，例如网络错误、超时错误等
    if(error.toString().contains("timeout")){
      BrnToast.show("网络请求超时", context);
    }else  if(error.toString().contains("Connection failed")){
      BrnToast.show("服务器请求失败", context);
    }else  if(error.toString().contains("connection error")){
      BrnToast.show("服务器请求错误", context);
    }else{
      BrnToast.show(error.toString(), context);
    }
    print(error.toString());
  }
}